package com.pfzy.utildemo.activity.record.soundrecord;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

//import com.pfzy.sdk.basis.tool.utils.ProcessUtil;
//import com.pfzy.sdk.soundrecord.constatns.CallbackConstant;
//import com.pfzy.sdk.soundrecord.db.DbManager;
//import com.pfzy.sdk.soundrecord.helper.CallBackHelper;
//import com.pfzy.sdk.soundrecord.upload.UpLoadManager;
//import com.pfzy.sdk.soundrecord.util.EnvironmentCheckUtil;
//import com.pfzy.sdk.soundrecord.util.FileSizeUtil;
//import com.pfzy.sdk.soundrecord.util.Logger;

import com.pfzy.lib.sdk.permission.UXPermission;
import com.pfzy.lib.sdk.permission.callback.PermissionCallBack;
import com.pfzy.utildemo.activity.record.sdk.pcm.RecordHelper;
import com.pfzy.utildemo.activity.record.soundrecord.constatns.CallbackConstant;
import com.pfzy.utildemo.activity.record.soundrecord.db.DbManager;
import com.pfzy.utildemo.activity.record.soundrecord.helper.CallBackHelper;
import com.pfzy.utildemo.activity.record.soundrecord.upload.UpLoadManager;
import com.pfzy.lib.config.log.MyLog;
import com.pfzy.utildemo.activity.record.soundrecord.util.EnvironmentCheckUtil;
import com.pfzy.utildemo.activity.record.soundrecord.util.FileSizeUtil;
import com.pfzy.utildemo.utils.ProcessUtil;

import java.util.List;
import java.util.concurrent.ExecutorService;

public class UxSoundRecordApi {
    private static final long START_OPERATOR_TIME_INTERNAL = 1000;// 启动操作时间间隔
    private static UxSoundRecordApi mInstance = null;
    private static long sStartTimeStamp = 0;
    private Context mContext;

    public static UxSoundRecordApi getInstance(Context context) {
        if (mInstance == null) {
            synchronized (UxSoundRecordApi.class) {
                if (mInstance == null) {
                    mInstance = new UxSoundRecordApi(context);
                }
            }
        }
        return mInstance;
    }

    private UxSoundRecordApi(Context context) {
        this.mContext = context;
    }

    /**
     * 切换到AAC
     */
    public static void switchToAAC(boolean aac) {
        MyLog.logd("录音API " + "switchToAAC : " + aac);
        SoundRecordSwitch.switchAAC(aac);
    }

    public void init(String capHost) {
        try {
            if (ProcessUtil.isMainProcess(this.mContext)) {
                _logd("主进程 init() = " + capHost + "\t 当前版本=1.5.0");
                // 数据管理器初始化
                DbManager.getInstance().init(this.mContext);
                // 上传管理器初始化
                UpLoadManager.init(this.mContext, capHost);
                // 启动检查上传
                startCheckRunnable();
            } else {
                _logd("不在主进程，不会进行初始化 Thread=" + Thread.currentThread());
            }
        } catch (Exception e) {
            _logd("初始化接口发生异常 " + e.toString());
        }
    }

    public boolean isRecording() {
        return RecordHelper.getInstance().isRecording();
    }

    @Nullable
    public RecordingInfo getCurrentRecording() {
        return RecordHelper.getInstance().getCurrentRecordInfo();
    }

    public boolean isRecording(String orderNo, String uid, int utype) {
        RecordingInfo tmpInfo;
        return RecordHelper.getInstance().isRecording() && (tmpInfo = RecordHelper.getInstance().getCurrentRecordInfo()) != null && TextUtils.equals(orderNo, tmpInfo.getOrderNo()) && TextUtils.equals(uid, tmpInfo.getUid());
    }

    // 启动录音
    public boolean start(RecordingInfo recordingInfo, boolean isApplyPermission, Activity activity, @Nullable SoundRecordCallback callback) {
        if (System.currentTimeMillis() - sStartTimeStamp < START_OPERATOR_TIME_INTERNAL) {
            _logd("调用 过于频繁");
            CallBackHelper.execOnFail(recordingInfo, CallbackConstant.FailInfo.OPERATION_TOO_FREQUENTLY, callback);
            return false;
        }

        boolean useAAC = SoundRecordSwitch.isUseAAC();
        _logd("start current orderNo : " + recordingInfo.getOrderNo() + " useAAC : " + useAAC);
        sStartTimeStamp = System.currentTimeMillis();

        if (isRecording()) {
            _logd("当前正在录音");
            CallBackHelper.execOnFail(recordingInfo, CallbackConstant.FailInfo.CURRENT_HAS_BEEN_RECORDING, callback);
            return false;
        } else if (!EnvironmentCheckUtil.isStorageSpaceEnough()) {
            _logd("存储空间不够, 可用空间 =" + FileSizeUtil.getInternalStorageAvailableSpace());
            CallBackHelper.execOnFail(recordingInfo, CallbackConstant.FailInfo.STORAGE_SPACE_NOT_ENOUGH, callback);
            return false;
        } else if (!isHaveRecordPermission(activity) && !isApplyPermission) {
            _logd("没有录音权限, 并且也不会主动申请");
            CallBackHelper.execOnFail(recordingInfo, CallbackConstant.FailInfo.NO_RECORD_AUDIO_PERMISSION_WITHOUT_APPLY, callback);
            return false;
        } else {
            CallBackHelper.sCallBack = callback;
            if (isHaveRecordPermission(activity)) {
                // 准备开始录制
                prepareStartRecording(activity, recordingInfo);
            } else {
                applyPermission(recordingInfo, activity);
            }
            return true;
        }
    }

    /**
     * 停止录音
     */
    public void stop(@Nullable RecordingInfo recordingInfo) {
        _logd( "stopRecording recordingInfo : " + (recordingInfo == null ? "" : recordingInfo.toString()));
        if (isRecording()) {
            Intent intent = new Intent(this.mContext, RecordingService.class);
            intent.setAction(RecordingService.ACTION_STOP_RECORD);
            intent.putExtra(RecordingService.KEY_TRANSMIT_DATA_TO_SERVICE, recordingInfo);
            this.mContext.startService(intent);
        }
        sStartTimeStamp = 0L;
    }

    public boolean isHaveRecordPermission(Activity activity) {
        if (ContextCompat.checkSelfPermission(activity, "android.permission.RECORD_AUDIO") == 0) {
            _logd("拥有录音权限   ---- yes");
            return true;
        }
        _logd("没有录音权限   --- no");
        return false;
    }

    /**
     * 准备开始录制
     */
    public void prepareStartRecording(Activity activity, RecordingInfo info) {
        if (!isHaveRecordPermission(activity) || !EnvironmentCheckUtil.validateMicAvailability()) {
            _logd( "麦克风被占用了, 或没权限");
            CallBackHelper.execOnFailAndClearAndSetIsRecording(info, CallbackConstant.FailInfo.MIC_NOT_AVAILABLITY);
            return;
        }
        // 实际开始录制
        actualStartRecording(info);
    }

    /**
     * 实际开始录制
     */
    private void actualStartRecording(RecordingInfo recordingInfo) {
        _logd( "actualStartRecording recordingInfo : " + (recordingInfo == null ? "" : recordingInfo.toString()));
        Intent intent = new Intent(this.mContext, RecordingService.class);
        intent.setAction(RecordingService.ACTION_START_RECORD);
        intent.putExtra(RecordingService.KEY_TRANSMIT_DATA_TO_SERVICE, recordingInfo);
        this.mContext.startService(intent);
    }

    /**
     * 应用权限
     */
    private void applyPermission(final RecordingInfo recordingInfo, final Activity activity) {
        UXPermission.with(activity).permission("android.permission.RECORD_AUDIO").request(new PermissionCallBack() {
            @Override
            public void hasPermission(List<String> granted, boolean isAll) {
                _logd( "有录音权限，hasPermission()");
                // 准备开始录制
                prepareStartRecording(activity, recordingInfo);
            }

            @Override
            public void noPermission(List<String> denied, boolean quick) {
                super.noPermission(denied, quick);
                _logd("无录音权限 noPermission()");
                CallBackHelper.execOnFailAndClearAndSetIsRecording(recordingInfo, CallbackConstant.FailInfo.NO_RECORD_AUDIO_PERMISSION);
            }

            /**
             * 申请录音权限
             */
            @Override
            public void needCheckPermission() {
                super.needCheckPermission();
                _logd("需要检查录音权限  needCheckPermission()");
                prepareStartRecording(activity, recordingInfo);
            }
        });
    }

    /**
     * 启动检查上传
     * https://blog.csdn.net/ZGL_cyy/article/details/117843472
     */
    private void startCheckRunnable() {
        ExecutorService singleThreadExecutor = null;// 单线程线程池
        try {
            singleThreadExecutor.execute(new CheckUploadRunnable());
//            singleThreadExecutor.submit(new CheckUploadRunnable());
//        ScheduledExecutorService mCountPriceExecutor = Executors.newSingleThreadScheduledExecutor();
//        ScheduledFuture<?> mCountPriceFuture = mCountPriceExecutor.scheduleWithFixedDelay({countPrice(0)}, 5, 30, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void _logd(String msg) {
        MyLog.logd("录音API " + msg);
    }
    private void _loge(String msg) {
        MyLog.loge("录音API " + msg);
    }
}
